// 全局请求封装——也可像上述一样根据环境不同的判断
// const base_url = '/api';
 const base_url = 'https://www.nlpy.cn/prod';//开发环境https://www.nlpy.cn/login?redirect=/index
// const base_url = '你的测试环境url';//测试环境
// const base_url = '你的正式环境url';//正式环境
// 请求超时设置
const timeout = 30000;
export default (params) => {
	let url = params.url;
	let method = params.method || "get";
	let data = params.data || {};
	let token = uni.getStorageSync('token') ? JSON.parse(uni.getStorageSync('token')) : ''
	let header = {
		'Token': token || '',
		'Content-Type': 'application/json;charset=UTF-8',
		'Authorization': token||'Basic c2FiZXI6c2FiZXJfc2VjcmV0',
		...params.header
	};
 
 
 
	if (method === "post") {
		header['Content-Type'] = 'application/json';
	}
 
	return new Promise((resolve, reject) => {
		uni.request({
			url: base_url + url,
			method: method,
			header: header,
			data: data,
			timeout,
			success(response) {
				const {
					statusCode,
					data,
					errMsg
				} = response;
				if (statusCode == 200) {
					if (data.code === 200) {
						resolve(data);//需要根据后端实际接口返回数据层级去resolve
					} else if (data.code == -1) {
						console.log(data.msg)
						uni.showToast({
						      title: data.msg, // 确保 msg 是字符串，如果不是则使用 '未知错误'
							  icon: "none",
						      duration: 10000,
						    });
					} else {
						// uni.clearStorageSync();
						switch (data.code) {
							case 10086:
								uni.navigateTo({
									url: "/pages/login/login",
								});
								break;
							case 404:
								uni.showToast({
									title: '请求地址不存在...',
									duration: 2000,
								});
								break;
							default:
								uni.showToast({
									title: data.msg,
									duration: 2000,
									icon:'error'
								});
								break;
						}
					}
				} else if (statusCode == 401) {
					uni.navigateTo({
						url: "/pages/login/login",
					});
				}
				resolve(response) 
			},
			fail(err) {
				console.log(err, '网络超时');
				uni.showToast({
					title: err.msg.indexOf('request:fail') !== -1 ? '网络连接失败' : '网络连接失败',
					icon: "error",
					duration: 2000
				});
				reject(err);
			},
			complete() {
				// 不管成功还是失败都会执行
				uni.hideLoading();
				// uni.hideToast();
			}
		});
	});
};